import axios, { AxiosInstance } from "axios";
import { AxiosRequest } from "./types";
import CCLoading from "@/utils/http/loading";
import router from "@/router";
import { ElMessage } from "element-plus";
import { i18n } from "@/locale";
const useI18n: any = i18n.global;
const t = useI18n.t;
const ccLoading = new CCLoading();
import loginStore from "@/stores/login";
class HTTP {
  instance: AxiosInstance;
  requestNum: number = 0;
  constructor() {
    this.instance = axios.create({
      // baseURL: "",
      baseURL: "/api/",
      timeout: 1000 * 50,
    });
    this.interceptRequest();
    this.interceptResponse();
  }

  request(params: AxiosRequest) {
    if (params.formdata) {
      // 兼容参数params 和data
      params.data = this.json2formdata(params.data || params.params);
      if (params.params) delete params.params;
      delete params.formdata;
    }

    return this.instance(params);
  }

  json2formdata(params: { [x: string]: string | Blob }) {
    let query = "";
    if (Object.prototype.toString.call(params) === "[object Object]") {
      for (const KEY in params) {
        if (Object.prototype.hasOwnProperty.call(params, KEY)) {
          query += `${KEY}=${params[KEY]}&`;
        }
      }
    }
    return query.replace(/&$/g, "");
  }

  interceptRequest() {
    this.instance.interceptors.request.use((request: any) => {
      const token = window.localStorage.getItem("token") || "";
      if (request.url !== "ucenter/login") {
        request.headers["token"] = token;
      }
      if (!request.hideLoading) {
        //是否隐藏loading
        this.requestNum++;
        ccLoading.show();
      }
      return request;
    });
  }

  interceptResponse() {
    this.instance.interceptors.response.use(
      (response: any) => {
        let responseVal = response?.data?.data ?? {};
        if (!response.config.hideLoading) {
          //是否隐藏loading
          this.requestNum--;
        }
        if (!this.requestNum) {
          ccLoading.hide();
        }

        if (response.status === 200 && response.data.errno === 0) {
          if (response.config.openResponese) {
            responseVal = response?.data ?? {};
          }
          if (response.config.message) {
            let msg = t(`responseMsg.${response.data.errno}`);
            ElMessage.success(msg);
          }
          return responseVal;
        } else {
          let msg = t(`responseMsg.${response.data.errno}`);
          if (response.data.errno === 9104) {
            //登录过期回到登录页
            const useLogin = loginStore();
            useLogin.getLoginInfos();
            if (useLogin.form.autoLogin) {
              useLogin.login();
            } else {
              this.backLoginPage();
            }
          }
          if (response.data.errno === 9101) {
            this.backLoginPage();
          }
          this.requestNum = 0;
          ccLoading.hide();
          ElMessage.error(msg);

          return Promise.reject(response.data.errmsg);
        }
      },
      (error) => {
        //请求出错
        this.requestNum--;
        ElMessage.error(error);
        if (!this.requestNum) {
          ccLoading.hide();
        }
        return Promise.reject(error.response);
      },
    );
  }

  backLoginPage() {
    router.replace("/");
  }
}

export default HTTP;
